package com.cssiot.weixin.basic.util;

import java.io.FileInputStream;
import java.io.InputStream;
import java.security.KeyStore;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.TrustStrategy;
import org.apache.http.util.EntityUtils;
/**
 * 处理https请求和验证问题，带ssl证书
 * @author jacking
 *
 */
public class HttpsToolUtil {
	private static final String SEVER_JKS_PATH="D:/apache-tomcat-8.0.26-testHttps/doubleWay/tomcat.jks";
	private static final String SEVER_JKS_PASSWORD="123456";
	private static final String CLIENT_JKS_PATH="D:/apache-tomcat-8.0.26-testHttps/doubleWay/truststore.jks";
	private static final String CLIENT_JKS_PASSWORD="123456";
	/**
	 * 单向验证
	 * @return
	 * @throws Exception
	 */
	public static SSLContext getOneSSLContext() throws Exception {
		InputStream input = new FileInputStream(SEVER_JKS_PATH);
		KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
		// FileInputStream("D:/apache-tomcat-8.0.26-testHttps/oneWay/truststore.jks");
		ks.load(input, SEVER_JKS_PASSWORD.toCharArray());
		TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
		tmf.init(ks);
		SSLContext context = SSLContext.getInstance("TLSv1.2");
		// 这里只指定了受信任的证书（单向认证），如果是双向认证的话，则第一个参数不能为null
		context.init(null, tmf.getTrustManagers(), null);
		return context;
	}

	/**
	 * 双向验证
	 * @return
	 * @throws Exception
	 */
	public static SSLContext getDoubleSSLContext() throws Exception {
		KeyStore ks = KeyStore.getInstance("JKS");
		KeyStore tks = KeyStore.getInstance("JKS");
		InputStream ksIn =new FileInputStream(SEVER_JKS_PATH);
		InputStream tksIn =new FileInputStream(CLIENT_JKS_PATH);
		KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
		TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
		ks.load(ksIn, SEVER_JKS_PASSWORD.toCharArray());
		tks.load(tksIn,CLIENT_JKS_PASSWORD.toCharArray());
		kmf.init(ks, SEVER_JKS_PASSWORD.toCharArray());
		tmf.init(tks);
		SSLContext context = SSLContext.getInstance("TLSv1.2");
		// 这里只指定了受信任的证书（单向认证），如果是双向认证的话，则第一个参数不能为null
		context.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
		return context;
	}


	
	/**
	 * 单向验证且服务端的证书可信
	 */
	public static void oneClientConnection() throws Exception{
		HttpGet httpget = new HttpGet("https://localhost:8443/wx/hello/rest/123");
		HttpClientBuilder builder = HttpClients.custom();
		//单向验证
		builder.setSSLContext(getOneSSLContext());
		CloseableHttpClient httpclient = builder.build();
		CloseableHttpResponse response = httpclient.execute(httpget);
		int statusCode = response.getStatusLine().getStatusCode();
		if (statusCode >= 200 && statusCode < 300) {
			System.out.println("restGet请求返回成功");
		}
		HttpEntity entity = response.getEntity();
		String body = EntityUtils.toString(entity);
		System.out.println(body);
		response.close();
		httpclient.close();
		 
	}
	/**
	 * 双向验证
	 * 
	 * @throws Exception
	 */
	public static void doubleClientConnection() throws Exception {
		HttpClientBuilder builder = HttpClients.custom();
		builder.setSSLContext(getDoubleSSLContext());
		CloseableHttpClient httpclient = builder.build();
		HttpGet httpget = new HttpGet("https://localhost:8443/wx/hello/rest/123");
		CloseableHttpResponse response = httpclient.execute(httpget);
		int statusCode = response.getStatusLine().getStatusCode();
		if (statusCode >= 200 && statusCode < 300) {
			System.out.println("restGet请求返回成功");
		}
		HttpEntity entity = response.getEntity();
		String body = EntityUtils.toString(entity);
		System.out.println(body);
		response.close();
		httpclient.close();
	}
	/**
	 * 跳过证书,信任所有
	 * @throws Exception
	 */
	public static void jumpClientConnection() throws  Exception{
		//信任所有证书
		CloseableHttpClient httpClient = createSSLClientDefault();
		HttpGet get = new HttpGet("https://localhost:8443/wx/hello/rest/123");  
		CloseableHttpResponse response = httpClient.execute(get);
		int statusCode = response.getStatusLine().getStatusCode();
		if (statusCode >= 200 && statusCode < 300) {
			System.out.println("restGet请求返回成功");
		}
				 
	}

	/**
	 * 信任所有证书
	 * @return
	 */
	public static CloseableHttpClient createSSLClientDefault() {
		try {
		   SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
				// 信任所有
				public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
					return true;
				}
			}).build();
			SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);
			return HttpClients.custom().setSSLSocketFactory(sslsf).build();
		} catch (Exception e) {
			e.printStackTrace();
		}  
		return HttpClients.createDefault();
	}

	
	public static void main(String[] args) throws Exception {
        //单向验证且服务端的证书可信
//		oneClientConnection();
		//跳过证书,信任所有
//		jumpClientConnection();
       //双向验证
		doubleClientConnection();

		 
	}
}